from services.chat_service import ChatService
from fastapi import APIRouter, Depends, HTTPException, status
from schemas.chat import ChatRequest


router = APIRouter(prefix="/chat", tags=["chat"])

# 获取Agent回复
@router.post("")
async def chat_with_agent(request: ChatRequest):
    try:
        # 每次请求创建新的服务实例
        chat_service = ChatService()
        result = await chat_service.create_chat_response(
            request.userId,
            request.sessionId,
            request.message,
            request.username
        )
        
        return {
            "code": 200,
            "message": "成功生成Agent回复",
            "data": {
                "userId": request.userId,
                "sessionId": request.sessionId,
                "content": result["content"],
                "totalToken": result["totalToken"]
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail={
                "code": 500,
                "message": f"AI回复失败: {str(e)}",
                
            })

# 其他路由处理函数也需要修改为每次创建新实例
@router.get("/{userId}")
async def get_chat_history(userId:str, sessionId: str):
    try:
        chat_service = ChatService()
        history = await chat_service.get_chat_history(userId, sessionId)
        return {
            "code": 200,
            "message": "成功获取聊天记录",
            "data": history
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail={
                "code": 500,
                "message": f"获取聊天记录失败: {str(e)}",

            })
# 根据userId和sessionId清空聊天记录
@router.delete("/{userId}")
async def clear_chat_history(userId:str, sessionId: str):
    try:
        historyCount = await chat_service.clear_chat_history(userId, sessionId)
        return {
            "code": 200,
            "message": "成功清空聊天记录",
            "data": {"historyCount":historyCount}
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail={
                "code": 500,
                "message": f"清空聊天记录失败: {str(e)}" 
            })

@router.get("/session/{userId}")
async def get_user_sessions(userId: str):
    """获取用户的所有对话会话列表"""
    try:
        # 创建新的服务实例，与其他路由处理函数保持一致
        chat_service = ChatService()
        sessions = await chat_service.get_user_all_sessions(userId)
        return {
            "code": 200,
            "message": "成功获取用户会话列表",
            "data": sessions
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))